/*
 *  Copyright (c) 2022 李伟国
 *  online-judge is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2.
 *  You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *  See the Mulan PSL v2 for more details.
 */

package edu.platform.service.impl;

import edu.platform.config.ConfigSourceProperties;
import edu.platform.service.IJudgeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class JudgeServiceImpl implements IJudgeService {

    @Resource
    private ConfigSourceProperties configSourceProperties;

    /**
     * 终端运行测试代码
     * @param cmd 终端命令
     * @return 运行结果
     */
    @Override
    public List<Object> Running(String cmd) {
        List<Object> resultList = new ArrayList<>();
        try {
            ProcessBuilder builder = new ProcessBuilder(cmd.split(" "));
            builder.redirectErrorStream(true);
            Process process = builder.start();
            InputStream inputStream = process.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
            Object lines;
            while ((lines = br.readLine())!=null) {
                resultList.add(lines);
            }
            Runtime.getRuntime().exec("ls");
        } catch (Exception e) {
            e.printStackTrace();
        }
//        System.out.println(result);
        return resultList;
    }

    /**
     * 创建源代码文件
     *
     * @param code 代码
     * @return 文件名称
     */
    @Override
    public String createFile(String code, String filePrefix, String fileSuffix) {
        // 代码存放路径
        String codeResultRootPath = configSourceProperties.getCodeResultRootPath();
        // 建立一个不冲突的文件夹
        String dir = UUID.randomUUID().toString().replaceAll("-", "");
        // 建立文件
        File file = new File(codeResultRootPath + File.separator +
                dir + File.separator + filePrefix + fileSuffix);
        boolean mkdirs = file.getParentFile().mkdirs();
        // 写入文件
        try (FileWriter fileWriter = new FileWriter(file, false)) {
            fileWriter.write(code);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.getParent();
    }

}
